const router = require('koa-router')();
const moment = require('moment');

router.prefix('/travel');

//获取发布的旅行信息
router.get('/message',async(ctx,next)=>{
    let sql = 'select travel.userid,travel.content,travel.time,travel.image,user.id,user.image userImage,user.username from travel,user where user.id=travel.userid and travel.state=1'
    let result = await ctx.db.EXCUTE(sql)
    for(let i=0;i<result.length;i++){
        result[i].time = moment(result[i].time).format('YYYY-MM-DD HH:mm:ss');
    }
    ctx.body = {code:200,statue:'success',list:result}
})

//上传发布信息
router.post('/submit',async(ctx,next)=>{
    let {userid,content,image} = ctx.request.body;
    console.log(ctx.request.body);
    let time = new Date().toLocaleString();
    let code;
    let status;
    let sql = 'insert into travel(userid,content,time,image,state) values(?,?,?,?,0)'
    try{
        let result = await ctx.db.EXCUTE(sql,[userid,content,time,image])
        console.log(result.affectedRows)
        status = result.affectedRows === 1 ? 
          '发送成功':'发送失败 ';
        code = result.affectedRows === 1 ? 
          200:400;
      }catch(e){
        code = 400;
        status = '发送失败';
        console.log(e)
      } 
    ctx.body={code:code,status:status}

})

module.exports = router;